﻿package com.diandong.airfieldmanage.common.download;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;

import com.diandong.airfieldmanage.BuildConfig;
import com.diandong.airfieldmanage.utils.LogUtil;
import com.diandong.airfieldmanage.utils.ToastUtil;

import java.io.File;

import androidx.core.content.FileProvider;

/**
 * Created : Yx
 * Time : 2019/5/15 15:35
 * Describe :
 * 10.0版本注意：https://blog.csdn.net/yingchengyou/article/details/99717498
 * https://blog.csdn.net/honjane/article/details/94288585
 *   File file = new File(saveDir, saveName);
 *	file.exists():目标文件已存在
 *	!file.getParentFile().exists():目标文件所在路径不存在。file.getParentFile().mkdirs()：创建目录文件所在的目录
 *
 *// 判断目录或文件是否存在
 *        if (!file.exists()) {  // 不存在返回 false
 *            return flag;
 *        } else {
 *            // 判断是否为文件
 *            if (file.isFile()) {  // 为文件时调用删除文件方法
 *                file.delete();
 *            } else {  // 为目录时调用删除目录方法
 *                 //如果sPath不以文件分隔符结尾，自动添加文件分隔符
 *       		 if (!sPath.endsWith(File.separator)) {
 *           			 sPath = sPath + File.separator;
 *       		 }
 *		file.delete()
 *            }
 *        }
 *
 */
public class FileUtils {

    /**
     * 获得一个：存储路径File的路径
     */
    public static String mFile() {
        return mFilePath().getPath() + "/";
    }

    //构建文件夹及  按时间创建了一个空图片
    //10.0版本需要在Manifest中加:android:requestLegacyExternalStorage="true"
    public static File mFilePath() {
        //获得文件夹
        File takeImageFile;
        if (existSDCard()) {
            //SD卡存在
            takeImageFile = new File(Environment.getExternalStorageDirectory(), "/am_file/");
        } else {//不存在使用机身内存
            takeImageFile = Environment.getDataDirectory();
        }
        if (!takeImageFile.exists()) {//没有就先创建
            takeImageFile.mkdir();
        }

        return takeImageFile;
    }

    /**
     * 判断SDCard是否可用
     */
    public static boolean existSDCard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }


    /**
     * 安装应用
     *
     * @param mContext
     * @param downloadApk
     */
    public static void installApk(Context mContext, String downloadApk) {
        if (TextUtils.isEmpty(downloadApk)) {
            ToastUtil.showToastApplication("安装路径不能为空!");
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(downloadApk);
        LogUtil.iYx("安装路径==" + downloadApk);///storage/emulated/0/DCIM/QQ.apk
        Uri mUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//7,0 + ".file.provider"
            mUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".fileprovider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            mUri = Uri.fromFile(file);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//启动新任务栈安装
            //mUri = Uri.parse("file:///" + photoFile);//裁切后保存路径
        }
        intent.setDataAndType(mUri, "application/vnd.android.package-archive");
        mContext.startActivity(intent);

    }


    /**
     * 获取文件格式名
     */
    public static String getFormatName(String fileName) {
        //去掉首尾的空格
        fileName = fileName.trim();
        String s[] = fileName.split("\\.");
        if (s.length >= 2) {
            return s[s.length - 1];
        }
        return "";
    }
    /**
     * 根据路径打开文件
     *
     * @param context 上下文
     * @param path    文件路径
     */
    public static void openFileByPath(Context context, String path) {
        if (context == null || path == null)
            return;
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //设置intent的Action属性
        intent.setAction(Intent.ACTION_VIEW);
        //文件的类型
        String type = "";
        for (int i = 0; i < MATCH_ARRAY.length; i++) {
            //判断文件的格式
            if (path.toString().contains(MATCH_ARRAY[i][0].toString())) {
                type = MATCH_ARRAY[i][1];
                break;
            }
        }
        try {
            //设置intent的data和Type属性
            intent.setDataAndType(Uri.fromFile(new File(path)), type);
            //跳转
            context.startActivity(intent);
        } catch (Exception e) { //当系统没有携带文件打开软件，提示
            ToastUtil.showToastApplication("无法打开该格式文件!");
            e.printStackTrace();
        }
    }

    //建立一个文件类型与文件后缀名的匹配表
    private static final String[][] MATCH_ARRAY = {
            //{后缀名，    文件类型}
            {".3gp", "video/3gpp"},
            {".apk", "application/vnd.android.package-archive"},
            {".asf", "video/x-ms-asf"},
            {".avi", "video/x-msvideo"},
            {".bin", "application/octet-stream"},
            {".bmp", "image/bmp"},
            {".c", "text/plain"},
            {".class", "application/octet-stream"},
            {".conf", "text/plain"},
            {".cpp", "text/plain"},
            {".doc", "application/msword"},
            {".exe", "application/octet-stream"},
            {".gif", "image/gif"},
            {".gtar", "application/x-gtar"},
            {".gz", "application/x-gzip"},
            {".h", "text/plain"},
            {".htm", "text/html"},
            {".html", "text/html"},
            {".jar", "application/java-archive"},
            {".java", "text/plain"},
            {".jpeg", "image/jpeg"},
            {".jpg", "image/jpeg"},
            {".js", "application/x-javascript"},
            {".log", "text/plain"},
            {".m3u", "audio/x-mpegurl"},
            {".m4a", "audio/mp4a-latm"},
            {".m4b", "audio/mp4a-latm"},
            {".m4p", "audio/mp4a-latm"},
            {".m4u", "video/vnd.mpegurl"},
            {".m4v", "video/x-m4v"},
            {".mov", "video/quicktime"},
            {".mp2", "audio/x-mpeg"},
            {".mp3", "audio/x-mpeg"},
            {".mp4", "video/mp4"},
            {".mpc", "application/vnd.mpohun.certificate"},
            {".mpe", "video/mpeg"},
            {".mpeg", "video/mpeg"},
            {".mpg", "video/mpeg"},
            {".mpg4", "video/mp4"},
            {".mpga", "audio/mpeg"},
            {".msg", "application/vnd.ms-outlook"},
            {".ogg", "audio/ogg"},
            {".pdf", "application/pdf"},
            {".png", "image/png"},
            {".pps", "application/vnd.ms-powerpoint"},
            {".ppt", "application/vnd.ms-powerpoint"},
            {".prop", "text/plain"},
            {".rar", "application/x-rar-compressed"},
            {".rc", "text/plain"},
            {".rmvb", "audio/x-pn-realaudio"},
            {".rtf", "application/rtf"},
            {".sh", "text/plain"},
            {".tar", "application/x-tar"},
            {".tgz", "application/x-compressed"},
            {".txt", "text/plain"},
            {".wav", "audio/x-wav"},
            {".wma", "audio/x-ms-wma"},
            {".wmv", "audio/x-ms-wmv"},
            {".wps", "application/vnd.ms-works"},
            {".xml", "text/plain"},
            {".z", "application/x-compress"},
            {".zip", "application/zip"},
            {"", "*/*"}
    };
}
